import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Col, Row, Input, Button, notification, message, DatePicker, Switch } from 'antd';
import moment from 'moment';
import { FormComponentProps } from "antd/lib/form/Form";
import { setUp, scheduleDetail } from './service';
import { checkInit, isNumber } from '@/utils/util';
import { DividerItem } from '@/components/DividerItem';

interface Props extends FormComponentProps {
  dispatch?: Function,
  data?: {
    id: string;
    isEnable: string;
    advanceStartTime: string;
    advanceCycle: string;
    advancePatrolTimes: string;
  };
  keys?: Array<string>;
}

interface State {
  isNew: boolean;
  confirmDirty: boolean;
  autoCompleteResult: {
    id: string;
    alarmRate: string;
    completeRate: string;
    advanceStartTime: string;
    advanceCycle: string;
    advancePatrolTimes: string;
    nextScanPatrolTime: string;
    startTime: string;
    isEnable: string;
  }
}

@connect()
class PatrolSchedule extends Component<Props, State> {
  state = {
    confirmDirty: false,
    autoCompleteResult: {
      id: null,
      alarmRate: '',
      completeRate: '',
      advanceStartTime: '',
      advanceCycle: '',
      advancePatrolTimes: '',
      nextScanPatrolTime: '',
      startTime: '',
      isEnable: ''
    },
    isNew: true
  };

  componentDidMount() {
    const { form } = this.props;
    checkInit();
    scheduleDetail().then((data) => {
      if (!data.errorMsg) {
        data.advanceStartTime = data.advanceStartTime ? moment(data.advanceStartTime, 'YYYY-MM-DD HH:mm') : null;
        this.setState({
          autoCompleteResult: data
        }, () => {
          let { alarmRate, completeRate, advanceStartTime, advanceCycle, advancePatrolTimes, nextScanPatrolTime, isEnable } = this.state.autoCompleteResult;
          form.setFieldsValue({
            alarmRate, completeRate, advanceStartTime, advanceCycle, advancePatrolTimes, nextScanPatrolTime,
            isEnable: isEnable === '1' ? true : false
          });
        })
      }
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form } = this.props;

    form.validateFields((err, values) => {
      if (!err) {
        values.advanceStartTime = values.advanceStartTime ? moment(values.advanceStartTime).format("YYYY-MM-DD HH:mm") : null;
        values.isEnable = ((values.isEnable === true) ? '1' : '0')
        setUp(values).then(() => {
          message.success('操作成功');
        }).catch(e => {
          console.log(e);

        }
        )
      } else {
        notification['error']({
          message: `巡逻周期设置不正确`,
          description: '每次巡逻时间的周期为15分钟的倍数',
        });
      }
    })
  };

  render() {
    const { form } = this.props;
    const { autoCompleteResult } = this.state;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };

    const Info = DividerItem('form', '巡逻设置')

    const ButtonList = () => (
      <Form.Item>
        <Button style={{ marginLeft: 20 }} onClick={() => {
          window.history.back()
        }}>取消</Button>
        <Button type="primary"
          htmlType="submit"
          style={{ marginLeft: 20 }}
          onClick={(e: any) => {
            this.handleSubmit(e)
          }}
        >保存</Button>
      </Form.Item>
    )

    return (
      <section>
        <Form onSubmit={this.handleSubmit}>
          <Info />
          <Row style={{ minHeight: '75vh' }}>
            <Col span={12}>
              {/* <Form.Item
                {...formItemLayout}
                label="告警率(0-1)"
              >
                {getFieldDecorator('alarmRate', {
                  rules: [{
                    required: true, message: '告警率',
                  }],
                })(
                  <Input placeholder='请输入告警率' type="number" />
                )}
              </Form.Item>
              <Form.Item
                {...formItemLayout}
                label='达标率(0-1)'
              >
                {getFieldDecorator('completeRate', {
                  rules: [{ required: true, message: '请输入达标率' }],
                })(
                  <Input placeholder='请输入达标率' type="number" />
                )}
              </Form.Item> */}

              <Form.Item
                {...formItemLayout}
                label='巡逻开始时间'
              >
                {getFieldDecorator('advanceStartTime', {
                  rules: [{ required: true, message: '开始时间' }],
                })(
                  <DatePicker
                    showTime={{ format: "HH:mm" }}
                    {...getFieldDecorator('advanceStartTime')}
                    format="YYYY-MM-DD HH:mm"
                    style={{ width: '100%' }}
                    placeholder="请选择开始时间"
                  />
                )}
              </Form.Item>
              {/* <Form.Item
                {...formItemLayout}
                label='巡逻周期(小时)'
              >
                {getFieldDecorator('advanceCycle', {
                  rules: [{ required: true, message: '巡逻周期' }],
                })(
                  <Input placeholder='请输入巡逻周期' type="number" />
                )}
              </Form.Item> */}
              <Form.Item
                {...formItemLayout}
                label='巡逻间隔(小时)'
              >
                {getFieldDecorator('advanceCycle', {
                  rules: [{ required: true, message: '巡逻间隔(小时)' }],
                })(
                  <Input placeholder='请输入巡逻间隔(小时)' min={1} type="number" />
                )}
              </Form.Item>
              {
                this.state.autoCompleteResult && this.state.autoCompleteResult.id && <Form.Item
                  {...formItemLayout}
                  label="下次巡逻时间"
                >
                  {getFieldDecorator('nextScanPatrolTime', {
                    rules: [{
                      required: true, message: '下次巡逻时间',
                    }],
                  })(
                    <Input placeholder='下次巡逻时间' disabled />
                  )}
                </Form.Item>
              }
              <Form.Item
                {...formItemLayout}
                label='开启巡逻'
              >
                {getFieldDecorator('isEnable', {
                  valuePropName: 'checked',
                  rules: [{ required: true }],
                })(
                  <Switch />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              {
                autoCompleteResult && autoCompleteResult.advanceStartTime
                && isNumber(Date.parse(new Date(autoCompleteResult.advanceStartTime).toString()))
                && (Date.parse(new Date(autoCompleteResult.advanceStartTime).toString()) !== Date.parse(new Date(autoCompleteResult.startTime).toString()))
                && (Date.parse(new Date(autoCompleteResult.advanceStartTime).toString()) > Date.parse(new Date().toString()))
                && <div>
                  <Col span={24} style={{ height: '40px', lineHeight: '40px', fontSize: 14 }}>预设下次巡逻时间：{moment(autoCompleteResult.advanceStartTime).format("YYYY-MM-DD HH:mm:ss")}</Col>
                  <Col span={24} style={{ height: '40px', lineHeight: '40px', fontSize: 14 }}>预设巡逻周期：{autoCompleteResult.advanceCycle}</Col>
                  <Col span={24} style={{ height: '40px', lineHeight: '40px', fontSize: 14 }}>预设巡逻次数：{autoCompleteResult.advancePatrolTimes}</Col>
                </div>
              }
            </Col>
          </Row>
          <Row><ButtonList /></Row>
        </Form>
      </section>
    );
  }
}

const FormList = Form.create<Props>()(PatrolSchedule);
export default FormList;
